﻿using HYDataCapture.Presenters;
using HYDataCapture.Views;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HY.WinForm;
using System.IO;

namespace HYDataCapture.Forms
{
    public partial class TaobaoShopAllGoodsCaptureForm : BaseForm, ITaobaoShopAllGoodsCaptureView
    {
        private TaobaoShopAllGoodsCapturePresenter _Presenter;

        private CefSharp.WinForms.ChromiumWebBrowser _wb;
        private bool _loading = false;
        private bool _HasInitWebBrowser;
        public TaobaoShopAllGoodsCaptureForm(ILogView log) : base(log)
        {
            InitializeComponent();

            _Presenter = new TaobaoShopAllGoodsCapturePresenter(this);
        }

        private void InitWebBrowser(string url)
        {
            _wb = new CefSharp.WinForms.ChromiumWebBrowser("");
            _wb.FrameLoadEnd += _wb_FrameLoadEnd;
            LoadUrl(url);
            _wb.Dock = DockStyle.Fill;
            tabPage1.Controls.Add(_wb);
        }

        private void _wb_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
        {
            Enabled = true;
            _Log.WriteLog("载入完成：" + e.Url);
            if(myButtonCheck1.Checked)
            {
                if (!_loading)
                {
                    _loading = true;
                    this.Invoke((EventHandler)delegate {
                        timer1.Interval = new Random().Next(3000, 5000);
                        timer1.Enabled = true;
                        _Log.WriteLog($"{timer1.Interval}毫秒后启动下一次采集...");
                    });

                }
            }
        }

        string[] ITaobaoShopAllGoodsCaptureView.GoodsTags
        {
            set
            {
                checkedListBox1.Items.AddRange(value);
            }
        }

        string[] ITaobaoShopAllGoodsCaptureView.SelectGoodsTags
        {
            get
            {
                List<string> valueList = new List<string>();
                for(int i=0;i<checkedListBox1.Items.Count;++i)
                {
                    if (checkedListBox1.GetItemChecked(i))
                        valueList.Add(checkedListBox1.Items[i].ToString());
                }
                return valueList.ToArray();
            }
        }

        string ITaobaoShopAllGoodsCaptureView.DataHtml
        {
            get
            {
                using (var task = _wb.GetSourceAsync())
                {
                    task.Wait();
                    return task.Result;
                }
            }
        }

        string ITaobaoShopAllGoodsCaptureView.Log
        {
            set
            {
                _Log.WriteLog(value);
            }
        }

        string ITaobaoShopAllGoodsCaptureView.SaleAmount
        {
            set
            {
                lbSaleAmount.Text = $"销售额：{value}";
            }
        }

        int ITaobaoShopAllGoodsCaptureView.CurrentIndex
        {
            set
            {
                if (value < dataGridView1.Rows.Count)
                    dataGridView1.FirstDisplayedScrollingRowIndex = value;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!_HasInitWebBrowser)
            {
                var util = new Utility();
                if (!util.ShopUrlCheck(cbUrl.Text, Enums.MenuEnums.TaobaoShopAllGoodsCapture))
                {
                    MessageBox.Show(util.ErrorMessage);
                    return;
                }
                _HasInitWebBrowser = true;
                InitWebBrowser(util.ShopAllGoodsUrl);
            }
            else
                LoadUrl(cbUrl.Text);
        }

        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemChecked(i, true);
            }
        }

        private void myButtonCheck1_Click(object sender, EventArgs e)
        {
            if(myButtonCheck1.Checked)
            {
                timer1.Enabled = true;
                _Presenter.Init();
                _Log.WriteLog("启动采集...");
            }
            else
            {
                _Log.WriteLog("正在停止采集...");
            }
        }

        private void LoadUrl(string url)
        {
            _loading = false;
            _wb.Load(url);
            _Log.WriteLog("载入：" + url);
            Enabled = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            switch(_Presenter.DataCapture())
            {
                case Enums.CaptureStateEnum.Success:
                    {
                        LoadUrl(_Presenter.NextUrl);
                    }
                    break;
                case Enums.CaptureStateEnum.Completed:
                    {
                        myButtonCheck1.Checked = false;
                        _Log.WriteLog("采集完成.");
                        tabControl1.SelectedIndex = 1;
                        using (DataGridViewBindData bind = new DataGridViewBindData(dataGridView1, delegate {
                            return _Presenter.Data;
                        })) ;
                        dataGridView1.RowHeadersWidth = 80;
                        this.toolStripStatusLabel1.Text = "记录数：" + _Presenter.Data.Rows.Count;
                    }
                    break;
                default:
                    {
                        myButtonCheck1.Checked = false;
                        _Log.WriteLog("采集已停止.");
                    }
                    break;
            }
        }

        private void TaobaoShopAllGoodsCaptureForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _wb.Delete();
            _wb.Dispose();
        }

        private void ExportExcel(Enums.ExportTypeEnum type)
        {
            using (var dlg = new SaveFileDialog())
            {
                switch (type)
                {
                    case Enums.ExportTypeEnum.Excel:
                        {
                            dlg.Filter = "Excel Files(*.xlsx)|*.xlsx";
                        }
                        break;
                    case Enums.ExportTypeEnum.ExcelWithImage:
                        {
                            dlg.Filter = "Excel Files(*.xls)|*.xls";
                        }
                        break;
                }
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(dlg.FileName))
                        try
                        {
                            File.Delete(dlg.FileName);
                        }
                        catch (Exception ex)
                        {
                            _Log.WriteLog("删除文件出错：" + ex.Message);
                            return;
                        }
                    switch (type)
                    {
                        case Enums.ExportTypeEnum.Excel:
                            _Presenter.ExportExcel(dlg.FileName);
                            break;
                        case Enums.ExportTypeEnum.ExcelWithImage:
                            _Presenter.ExportExcelWithGoodsImage(dlg.FileName);
                            break;
                    }
                }
            }
        }

        private void 导出为ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportExcel(Enums.ExportTypeEnum.Excel);
        }
        private void 导出为Excel包含商品图片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportExcel(Enums.ExportTypeEnum.ExcelWithImage);
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var dlg = new Dialogs.HelpDialog( Enums.HelpTypeEnum.WhatIsTaobaoShopUrl))
            {
                dlg.WindowState = FormWindowState.Maximized;
                dlg.ShowDialog();
            }
        }

        private void 更新已售件数为实际月销量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(_Presenter.InitUpdateSaleNum())
            {
                LoadUrl(_Presenter.NextUrl);
                myButtonCheck1.Checked = true;
                _Log.WriteLog("启动采集...");
            }
        }

        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }
    }
}
